#include <stdlib.h>
#include <iostream>
#include <stdio.h>

using namespace std;

#include "Hfile.h"
    
int char2short(char c){
    if((c >= '0' )&&( c<= '9'))
        return c-'0';
    if((c >= 'A' )&&( c<= 'F'))
        return c-'A'+ 10;
    if((c >= 'a' )&&( c<= 'f'))
        return c-'a'+ 10;    
    return 0;
}


int str2short(char * c){
     return char2short(c[0])*16 + char2short(c[1]);    
}


int getLineLength(char * line){
    int i ;
    for (i=0;;i++){
        if (((line[i]>='0')&&(line[i]<='9')) || ((line[i]>='a')&&(line[i]<='z')) || ((line[i]>='A')&&(line[i]<='Z')) || (line[i]==':')){
        } else{
            return i;
        }
    }
}


Hfile::Hfile(const char* file_name, const char* type){
    _fp = fopen(file_name, type);
    if (!_fp) {//can not open file, close socket, return
        cout<<"cannot open input file"<<endl;
        fclose(_fp);
        exit(1);
    }
    _length = 0;
    _size = 0;
}


Hfile::~Hfile(){}


int Hfile::setSize(char* buf){
    char revh = (char)buf[4];
    char revl= (char)buf[5];
    int file_len = (buf[6]<<24) + (buf[7]<<16) + (buf[8]<<8) + (buf[9]);
    cout<<"File length:"<<file_len<<endl;
    _size = file_len;
}


int Hfile::getLength(){
    return _length;
}


int Hfile::getSize(){
    return _size;
}


int Hfile::writeFile(char* buf, int buf_len){
    fwrite(buf, sizeof(char), buf_len, _fp);
    _length = _length + buf_len;
}


int Hfile::fileLineCount() {
    int i;    
    static char line[1255];
    i=0;
    while(!feof(_fp)){
        fgets(line,1000,_fp);
        i++;
    }    
    rewind(_fp);
    return i;
}


int Hfile::getLineData(char* data, int* data_len, char* addr_low, char* addr_high) {
    static char line[2550];
    int packet_len;
    while (!feof(_fp)){
        fgets(line, 1000, _fp);
        int line_len = getLineLength(line);
        if((line_len > 0 )&& (line[0]== ':')){ 
            int _data_len = str2short(line + 1);
            *data_len = _data_len;
            packet_len = packet_len + _data_len;
            for (int i=0; i<_data_len; i++){
                data[i] = str2short(line + 9 + i*2);
            }
            char _addr_low = str2short(line+5);
            char _addr_high = str2short(line+3);
            *addr_low = _addr_low;
            *addr_high = _addr_high;
            return 1;
        } else{
            return -1;
        }
    }
    return 0;
}


int Hfile::refresh(){
    cout<<"---refresh----"<<endl;
    fflush(_fp);
    _length = 0;
    rewind(_fp);
}


int Hfile::closeFile(){
    fclose(_fp);
}
